<template>
  <div>
    <editor v-model="content" :init="init" :disabled="disabled"></editor>
  </div>
</template>

<script>
import {uploadFile, uploadFiles, previewFile} from '@/api/files/file'; // 引入文件上传接口
import {Message, Loading} from 'element-ui'; // 引入 Element UI 组件
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver";
import "tinymce/plugins/image";
import "tinymce/plugins/media";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/contextmenu";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/colorpicker";
import "tinymce/plugins/textcolor";
import "tinymce/plugins/preview";
import "tinymce/plugins/code";
import "tinymce/plugins/link";
import "tinymce/plugins/advlist";
import "tinymce/plugins/codesample";
import "tinymce/plugins/hr";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/textpattern";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/autolink";
import "tinymce/plugins/directionality";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/template";
import "tinymce/plugins/charmap";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/imagetools";
import "tinymce/plugins/autosave";
import "tinymce/plugins/autoresize";

import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';

export default {
  name: "EditorPlus",
  components: {
    Editor,
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default:
        "preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media code codesample table charmap hr nonbreaking insertdatetime advlist lists wordcount imagetools textpattern autosave autoresize file",
    },
    toolbar: {
      type: [String, Array],
      default:
        "code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link codesample | alignleft aligncenter alignright alignjustify outdent indent formatpainter | \
      styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
      table image media charmap hr pagebreak insertdatetime | fullscreen preview | file",
    },
  },
  data: function () {
    return {
      officeFileExtensions: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'],
      init: {
        menubar: true,
        language_url: `${process.env.BASE_URL}tinymce/langs/zh_CN.js`,
        language: "zh_CN",
        skin_url: `${process.env.BASE_URL}tinymce/skins/ui/oxide`,
        min_height: 250,
        max_height: 500,
        plugins: this.plugins + " file",
        toolbar: this.toolbar + " | file",
        content_style: "p {margin: 5px 0;}",
        fontsize_formats: "12px 14px 16px 18px 24px 36px 48px 56px 72px",
        font_formats:
          "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
        branding: false,
        extended_valid_elements: 'iframe[src|width|height|frameborder|allowfullscreen]', // 允许 iframe 标签
        valid_children: '+body[iframe]', // 允许 iframe 作为 body 的子元素
        // ...


        // 图片上传
        images_upload_handler: (blobInfo, success, failure) => {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());

          // 显示上传进度
          const loadingInstance = Loading.service({text: '图片上传中...', background: 'rgba(0, 0, 0, 0.7)'});

          uploadFile(formData)
            .then((res) => {
              loadingInstance.close();
              if (res.code === 200) {
                // 拼接完整的文件 URL
                const fileUrl = res.data[0].fileUrl;
                success(fileUrl); // 传递给 TinyMCE
              } else {
                Message.error(res.msg || '图片上传失败');
                failure(res.msg || '图片上传失败');
              }
            })
            .catch((error) => {
              loadingInstance.close();
              Message.error('图片上传出错');
              failure('图片上传出错');
            });
        },

        // 文件上传
        file_picker_callback: (callback, value, meta) => {
          const input = document.createElement("input");
          input.setAttribute("type", "file");
          input.setAttribute("accept", ".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx");

          input.onchange = () => {
            const file = input.files[0];
            const formData = new FormData();
            formData.append("file", file);

            // 显示上传进度
            const loadingInstance = Loading.service({text: '文件上传中...', background: 'rgba(0, 0, 0, 0.7)'});

            uploadFile(formData)
              .then((res) => {
                loadingInstance.close();
                if (res.code === 200) {
                  const fileUrl = res.data[0].fileUrl;
                  callback(fileUrl, {text: file.name});
                } else {
                  Message.error(res.msg || '文件上传失败');
                }
              })
              .catch((error) => {
                loadingInstance.close();
                Message.error('文件上传出错');
              });
          };

          input.click();
        },

        setup: (editor) => {
          editor.on('init', () => {
            const iframeDoc = editor.contentDocument || editor.getDoc();
            iframeDoc.addEventListener('click', (e) => {
              const target = e.target;
              if (target.tagName === 'A') {
                console.log('Link clicked:', target.getAttribute('href')); // 调试信息
                e.preventDefault();
                e.stopPropagation();

                const href = target.getAttribute('href');
                const id = href.split('/').pop();

                // 处理链接逻辑
                previewFile(id)
                  .then(response => {
                    const blobUrl = URL.createObjectURL(new Blob([response], {type: 'application/pdf'}));

                    const iframe = document.createElement('iframe');
                    iframe.src = blobUrl;
                    iframe.style.width = '100%';
                    iframe.style.height = '100%';

                    const previewWindow = window.open('', '_blank');
                    previewWindow.document.body.appendChild(iframe);

                    new Viewer(previewWindow.document.body, {
                      inline: true,
                      toolbar: {
                        zoomIn: true,
                        zoomOut: true,
                        rotateLeft: true,
                        rotateRight: true,
                      },
                    });
                  })
                  .catch(error => {
                    console.error('Error handling link:', error);
                    Message.error('文件预览失败');
                  });
              }
            });
          });
        },


        // setup: (editor) => {
        //   editor.on('click', (e) => {
        //     const target = e.target;
        //     if (target.tagName === 'A') {
        //       e.preventDefault(); // 阻止默认的链接跳转行为
        //       e.stopPropagation(); // 阻止事件冒泡
        //       const href = target.getAttribute('href');
        //       const id = href.split('/').pop(); // 提取文件 ID
        //
        //       // 调用预览接口获取 PDF 文件流
        //       previewFile(id)
        //         .then(response => {
        //           // 创建 Blob URL
        //           const blobUrl = URL.createObjectURL(new Blob([response], { type: 'application/pdf' }));
        //
        //           // 创建 iframe 嵌入 PDF
        //           const iframe = document.createElement('iframe');
        //           iframe.src = blobUrl;
        //           iframe.style.width = '100%';
        //           iframe.style.height = '100%';
        //
        //           // 打开新窗口或弹窗显示 iframe
        //           const previewWindow = window.open('', '_blank');
        //           previewWindow.document.body.appendChild(iframe);
        //
        //           // 初始化 Viewer.js
        //           new Viewer(previewWindow.document.body, {
        //             inline: true,
        //             toolbar: {
        //               zoomIn: true,
        //               zoomOut: true,
        //               rotateLeft: true,
        //               rotateRight: true,
        //             },
        //           });
        //         })
        //         .catch(error => {
        //           console.error('Error handling link:', error);
        //           Message.error('文件预览失败');
        //         });
        //     }
        //   });
        // },


        // // 设置点击事件监听器-预览非公共文件
        // setup: (editor) => {
        //   editor.on('click', (e) => {
        //     const target = e.target;
        //     if (target.tagName === 'A') {
        //       e.preventDefault(); // 阻止默认的链接跳转行为
        //       const href = target.getAttribute('href');
        //       const id = href.split('/').pop(); // 提取文件 ID
        //
        //       // 调用预览接口获取 PDF 文件流
        //       previewFile(id)
        //         .then(response => {
        //           const pdfBlob = new Blob([response], { type: 'application/pdf' });
        //           const blobUrl = URL.createObjectURL(pdfBlob);
        //
        //           // 使用 embed 标签
        //           const embed = document.createElement('embed');
        //           embed.src = blobUrl;
        //           embed.type = 'application/pdf';
        //           embed.style.width = '100%';
        //           embed.style.height = '100%';
        //
        //           // 打开新窗口或弹窗显示 embed
        //           const previewWindow = window.open('', '_blank');
        //           previewWindow.document.body.appendChild(embed);
        //         })
        //         .catch(error => {
        //           console.error('Error handling link:', error);
        //           Message.error('文件预览失败');
        //         });
        //     }
        //   });
        // },


        // // 设置点击事件监听器，预览公共文件
        // setup: (editor) => {
        //   editor.on('click', (e) => {
        //     const target = e.target;
        //     if (target.tagName === 'A') {
        //       console.log('Link clicked, preventing default behavior'); // 调试信息
        //       // e.preventDefault(); // 阻止默认的链接跳转行为
        //       const href = target.getAttribute('href');
        //       const id = href.split('/').pop(); // 1901850717333864450
        //
        //       previewFile(id)
        //         .then(response => {
        //           const fileUrl = response.data.fileUrl;
        //           const fileType = response.data.fileType;
        //           // 判断是否为 Office 文件
        //           if (this.officeFileExtensions.includes(fileType)) {
        //             // 调用预览文件接口获取文件 URL
        //             window.open(fileUrl, '_blank');
        //           } else {
        //
        //             // 处理其他类型的文件或链接
        //             this.handleLinkClick(id); // 调用自定义的链接处理函数
        //           }
        //
        //
        //         })
        //
        //     }
        //   });
        // },


      },
      content: this.value,
    };
  },
  mounted() {
    tinymce.init({});
  },
  methods: {
    handleLinkClick(id) {
      // 调用自定义的接口处理链接访问
      previewFile(id)
        .then(response => {
          // 处理接口返回的结果
          console.log('Link handled:', response.data);
          // 你可以在这里执行一些操作，比如打开一个新窗口显示链接内容
          window.open(response.data.redirectUrl, '_blank');
        })
        .catch(error => {
          console.error('Error handling link:', error);
        });
    }
  },
  watch: {
    value(newValue) {
      this.content = newValue;
    },
    content(newValue) {
      this.$emit("input", newValue);
    },
  },
};
</script>

<style scoped lang="scss"></style>
<style lang='scss'>
/* 设置tinymce的弹出层的层级为 9999 */
.tox-tinymce-aux {
  z-index: 9999 !important;
}
</style>
